const { whisper, info } = require("../utils/log_tool");
const { svn_is_dirty } = require("../utils/scm_tool");
const { exec_shell } = require("../utils/shell_tool");
const { BaseCommand } = require("./base");

class SvnCommitCommand extends BaseCommand {
    async execute() {
        const data = this.selfData;
        if (!data.force) {
            const is_dirty = await svn_is_dirty(data.cwd);
            if (!is_dirty) {
                whisper(`没有要svn提交的更改 ${data.cwd} ${data.msg}`);
                return;
            } else {
                if (data.remove_missing) {
                    const missingFiles = is_dirty
                        .split(/[\r\n]{1,2}/)
                        .filter((v) => v && v[0] === "!")
                        .map((v) => v.split(/\s+/)[1]);
                    if (missingFiles.length) {
                        info(`删除svn丢失文件 ${data.cwd}`);
                        await exec_shell({
                            cmd: "svn rm".split(" ").concat(missingFiles),
                            cwd: data.cwd,
                        });
                    }
                    // 移除文件时要update
                    await exec_shell({
                        cmd: "svn update",
                        cwd: data.cwd,
                    });
                }
                info(`准备svn提交 ${data.cwd} ${data.msg}`);
                if (data.credential) {
                    await exec_shell({
                        cmd: `svn commit --username ${data.credential.username} --password ${data.credential.password}  -m`
                            .split(" ")
                            .concat(data.msg),
                        cwd: data.cwd,
                    });
                } else {
                    await exec_shell({
                        cmd: "svn commit -m".split(" ").concat(data.msg),
                        cwd: data.cwd,
                    });
                }
            }
        }
    }
}

module.exports = {
    SvnCommitCommand,
};
